<template>
  <div class="login-container">
    <div class="login-wrapper">
      <!-- 头部logo区域 -->
      <div class="login-header">
        <div class="logo-section">
          <div class="logo-placeholder">
            <el-icon size="60" color="#409EFF">
              <School />
            </el-icon>
          </div>
          <h1 class="system-title">毕业论文智能查重系统</h1>
          <p class="system-subtitle">Graduation Paper Intelligent Plagiarism Detection System</p>
        </div>
      </div>

      <!-- 登录表单区域 -->
      <div class="login-form-container">
        <el-card class="login-card" shadow="hover">
          <div class="form-header">
            <h2>用户登录</h2>
            <p>请输入您的学号/工号和密码</p>
          </div>

          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            @submit.prevent="handleLogin"
          >
            <el-form-item prop="account">
              <el-input
                v-model="loginForm.account"
                placeholder="请输入学号/工号"
                size="large"
                clearable
                :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                show-password
                clearable
                :prefix-icon="Lock"
                @keyup.enter="handleLogin"
              />
            </el-form-item>

            <el-form-item>
              <div class="form-options">
                <el-checkbox v-model="loginForm.rememberMe">
                  记住我
                </el-checkbox>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                class="login-btn"
                @click="handleLogin"
              >
                {{ loading ? '登录中...' : '登录' }}
              </el-button>
            </el-form-item>

            <el-form-item>
              <div class="form-footer">
                <span>还没有账号？</span>
                <el-link type="primary" @click="$router.push('/register')">
                  立即注册
                </el-link>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>

    <!-- 背景装饰 -->
    <div class="login-background">
      <div class="bg-shape shape-1"></div>
      <div class="bg-shape shape-2"></div>
      <div class="bg-shape shape-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeMount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User, Lock, School } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { login } from '@/api/auth'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const appStore = useAppStore()

// 表单引用
const loginFormRef = ref()

// 加载状态
const loading = ref(false)

// 登录表单数据
const loginForm = ref({
  account: '',
  password: '',
  rememberMe: false
})

// 表单验证规则
const loginRules = {
  account: [
    { required: true, message: '请输入学号/工号', trigger: 'blur' },
    { 
      min: 3, 
      message: '账号长度不能少于3位', 
      trigger: 'blur' 
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    // 表单验证
    await loginFormRef.value.validate()
    
    loading.value = true
    
    console.log('开始真实登录流程...')
    console.log('发送登录请求:', {
      account: loginForm.value.account,
      password: loginForm.value.password
    })
    
    // 直接调用真实登录API
    const response = await login({
      account: loginForm.value.account,
      password: loginForm.value.password
    })
    
    console.log('真实API响应:', response)
    
    // 修改判断逻辑：直接检查是否有 token
    if (response && response.token) {
      const { token, userInfo, expiresIn } = response
      
      console.log('真实登录成功:', {
        token: token ? `有token (${token.substring(0, 20)}...)` : '无token',
        userInfo,
        expiresIn
      })
      
      // 保存登录信息到store
      console.log('保存登录信息到store...')
      userStore.login(token, userInfo)

      // 添加调试信息
      console.log('保存后的本地存储状态:', {
        localStorageToken: localStorage.getItem('graduation_check_token'),
        localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
        sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
        sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
      })

      // 立即验证存储状态
      setTimeout(() => {
        console.log('延迟100ms验证存储状态:', {
          localStorageToken: localStorage.getItem('graduation_check_token'),
          localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
          sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
          sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
        })
      }, 100)

      // 等待一段时间确保存储完成
      await new Promise(resolve => setTimeout(resolve, 200))
      
      // 再次检查本地存储
      console.log('再次检查本地存储:', {
        localStorageToken: localStorage.getItem('graduation_check_token'),
        localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
        sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
        sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
      })
      
      // 记住账号
      if (loginForm.value.rememberMe) {
        userStore.rememberAccount(loginForm.value.account)
      } else {
        userStore.rememberAccount('')
      }
      
      ElMessage.success('登录成功')
      
      // 检查store状态
      console.log('检查store状态:', {
        isLoggedIn: userStore.isLoggedIn,
        token: userStore.token,
        userInfo: userStore.userInfo
      })
      
      // 根据用户类型直接跳转到对应的工作台
      const userType = userStore.userInfo?.userType
      let redirectPath = route.query.redirect
      
      if (!redirectPath) {
        // 如果没有指定重定向路径，根据用户类型跳转到对应的工作台
        if (userType === 'S') {
          redirectPath = '/student/dashboard'
        } else if (userType === 'T') {
          redirectPath = '/teacher/dashboard'
        } else {
          // 默认跳转到学生工作台
          redirectPath = '/student/dashboard'
        }
      }
      
      console.log('准备跳转到:', redirectPath, '用户类型:', userType)
      
      // 使用路由跳转
      console.log('设置定时器检查存储状态')

      // 立即检查
      setTimeout(() => {
        console.log('5秒后检查存储状态:', {
          localStorageToken: localStorage.getItem('graduation_check_token'),
          localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
          sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
          sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
        })
      }, 5000)

      // 10秒后再次检查
      setTimeout(() => {
        console.log('10秒后再次检查存储状态:', {
          localStorageToken: localStorage.getItem('graduation_check_token'),
          localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
          sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
          sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
        })
      }, 10000)

      // 30秒后再次检查
      setTimeout(() => {
        console.log('30秒后再次检查存储状态:', {
          localStorageToken: localStorage.getItem('graduation_check_token'),
          localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
          sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
          sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
        })
      }, 30000)

      router.push(redirectPath).then(() => {
        console.log('跳转成功到:', redirectPath)
      }).catch(err => {
        console.error('跳转失败:', err)
        // 如果跳转失败，尝试使用 replace
        router.replace(redirectPath)
      })
      console.log('跳转指令已发送')
      
    } else {
      // 处理业务逻辑错误
      console.error('登录业务逻辑错误:', response)
      ElMessage.error('登录失败，请检查账号密码')
    }
    
  } catch (error) {
    console.error('登录捕获到异常:', error)
    
    // 显示具体的错误信息
    if (error.response) {
      const { data, status } = error.response
      console.error('服务器错误响应:', { status, data })
      
      if (status === 401) {
        ElMessage.error('账号或密码错误')
      } else if (status === 403) {
        ElMessage.error('没有访问权限')
      } else if (status === 404) {
        ElMessage.error('接口不存在: ' + error.config.url)
      } else if (status === 500) {
        ElMessage.error('服务器内部错误')
      } else {
        ElMessage.error(data?.message || `请求失败: ${status}`)
      }
    } else if (error.request) {
      console.error('网络请求错误:', error.request)
      ElMessage.error('网络连接失败，请检查网络连接')
    } else {
      console.error('其他错误:', error.message)
      ElMessage.error(error.message || '登录失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 页面加载时设置记住的账号
onBeforeMount(() => {
  // 页面加载时检查是否有存储的登录信息
  const storedToken = localStorage.getItem('graduation_check_token') || sessionStorage.getItem('graduation_check_token')
  const storedUserInfo = localStorage.getItem('graduation_check_user_info') || sessionStorage.getItem('graduation_check_user_info')
  
  console.log('页面加载时检查存储状态:', {
    storedToken: storedToken ? `${storedToken.substring(0, 20)}...` : '无',
    storedUserInfo
  })
  
  // 如果有存储的登录信息，尝试恢复登录状态
  if (storedToken && storedToken.length > 0 && storedUserInfo) {
    try {
      const userInfo = JSON.parse(storedUserInfo)
      userStore.login(storedToken, userInfo)
      console.log('页面加载时已恢复登录状态')
    } catch (e) {
      console.error('页面加载时恢复登录状态失败:', e)
    }
  }
})

onMounted(() => {
  const rememberedAccount = userStore.getRememberedAccount()
  if (rememberedAccount) {
    loginForm.value.account = rememberedAccount
    loginForm.value.rememberMe = true
  }
  
  // 设置页面标题
  appStore.setPageTitle('用户登录')
})
</script>


<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.login-wrapper {
  width: 100%;
  max-width: 800px;
  z-index: 10;
}

/* 头部logo区域 */
.login-header {
  text-align: center;
  margin-bottom: 2rem;
}

.logo-section {
  color: white;
}

.logo-placeholder {
  margin-bottom: 1rem;
}

.system-title {
  font-size: 3rem;
  font-weight: 600;
  margin: 0 0 0.5rem 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.system-subtitle {
  font-size: 0.9rem;
  opacity: 0.9;
  margin: 0;
}

/* 登录表单区域 */
.login-form-container {
  padding: 0 1rem;
}

.login-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.15);
  padding: 2rem;
}

.form-header {
  text-align: center;
  margin-bottom: 2rem;
}

.form-header h2 {
  color: #303133;
  margin: 0 0 0.5rem 0;
  font-weight: 600;
}

.form-header p {
  color: #909399;
  margin: 0;
  font-size: 0.9rem;
}

.login-form {
  padding: 0 1rem;
}

.form-options {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 1rem;
  font-weight: 500;
  border-radius: 8px;
}

.form-footer {
  text-align: center;
  font-size: 0.9rem;
  color: #909399;
}

/* 背景装饰 */
.login-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
}

.bg-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 120px;
  height: 120px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 80px;
  height: 80px;
  top: 70%;
  right: 10%;
  animation-delay: 2s;
}

.shape-3 {
  width: 160px;
  height: 160px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
}

/* PC端优化设计 */
@media (max-width: 1200px) {
  .login-wrapper {
    max-width: 550px;
  }
}

@media (max-width: 992px) {
  .login-wrapper {
    max-width: 500px;
  }
  
  .system-title {
    font-size: 2.2rem;
  }
  
  .system-subtitle {
    font-size: 1rem;
  }
}

@media (max-width: 768px) {
  .login-wrapper {
    max-width: 90%;
  }
  
  .system-title {
    font-size: 1.5rem;
  }
  
  .system-subtitle {
    font-size: 0.8rem;
  }
  
  .login-form {
    padding: 0;
  }
}
</style>